﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml.Linq;

namespace Infrastructure
{
    public class StateMachine
    {
        private readonly static Dictionary<String, State> _states = new Dictionary<String, State>();

        public static void SetupStateMachineFromXml(string xmlFile)
        {

            Assembly containerDll = Assembly.LoadFrom("RegCustomer.dll");

            XElement root = XElement.Load(xmlFile);

            var xmlStates = root.Elements("States").First();
            foreach (var xmlState in xmlStates.Elements())
            {
                State state = new State(xmlState.Name.LocalName);

                if (xmlState.Attributes("InitialState").Count() > 0)
                {
                    XAttribute initialState = xmlState.Attributes("InitialState").First();

                    if (initialState != null &&
                        String.Equals(initialState.Value, "true", StringComparison.OrdinalIgnoreCase))
                        StateMachine.InitialState = state;
                }

                StateMachine.AddState(state);
            }

            foreach (var xmlState in xmlStates.Elements())
            {
                foreach (var eventName in xmlState.Elements())
                {
                    var eventType = containerDll.GetType(containerDll.GetName(true).Name
                        + "." + eventName.Name.LocalName);
                    if (eventType == null)
                        throw new ApplicationException(
                            string.Format("The Event {0} was not found in the {1} assembly.",
                            eventName.Name.LocalName,
                            containerDll.GetName(true).Name));

                    StateMachine.States[xmlState.Name.LocalName]
                        .AddTransition(eventType,
                            StateMachine.States[eventName.Attribute("NextState").Value]);
                }
            }

        }

        public static Dictionary<String, State> States
        {
            get
            {
                return _states;
            }
        }

        public static void AddState(State state)
        {
            _states.Add(state.Name, state);
        }
        public static State InitialState { get; set; }

        private int myVar;

        public int MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }
        
    }
}
